package com.stone.mythread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 解决现存安全问题方式三
 */
public class LockTest implements Runnable {

    private int ticket = 100;

    // 1、实例化锁对象
    private ReentrantLock lock = new ReentrantLock(true);

    @Override
    public void run() {
        while (true) {
            // 2、调用 lock() 方法
            lock.lock();
            try {
                if (ticket > 0) {
                    System.err.println(Thread.currentThread().getName() + ": 售票，票号 ： " + ticket);
                    ticket--;
                } else {
                    break;
                }
            } finally {
                // 3、调用解锁方法
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        LockTest lockTest = new LockTest();
        Thread w1 = new Thread(lockTest);
        Thread w2 = new Thread(lockTest);
        Thread w3 = new Thread(lockTest);

        w1.setName("窗口一");
        w2.setName("窗口二");
        w3.setName("窗口三");

        w1.start();
        w2.start();
        w3.start();
    }
}
